package com.car.advertising.activity.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.car.advertising.R;
import com.car.advertising.activity.MainHomeActivity;
import com.car.advertising.activity.ProjectFilterActivity;
import com.car.advertising.activity.TaskDetailsActivity;
import com.car.advertising.activity.adapter.ProjectAdapter;
import com.car.advertising.connection.HttpUrl;
import com.car.advertising.entity.TaskRecordEntity;
import com.car.advertising.view.PagerGalleryView;
import com.support.widget.JumpManager;
import com.support.widget.interfacelistener.OnRecyclerViewItemClickListener;
import com.support.widget.layout.fragment.BaseScrollviewFreshFragment;
import com.support.widget.network.OkHttpClientManager;
import com.support.widget.util.LogUtil;
import com.support.widget.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 首页
 */
public class HomePageFragment extends BaseScrollviewFreshFragment {

    private MainHomeActivity homeActivity;
    private RelativeLayout selectedLookRl;
    private RelativeLayout limitedLookRl;
    private RelativeLayout timeLimitLookRl;
    private RecyclerView selectedRlv;
    private RecyclerView limitedRlv;
    private RecyclerView timeLimitRlv;
    private RelativeLayout understandRl;

    private List<TaskRecordEntity> homeSelectedtList = new ArrayList<>();
    private List<TaskRecordEntity> homeLimitedList = new ArrayList<>();
    private List<TaskRecordEntity> homeTimeLimittList = new ArrayList<>();
    private ProjectAdapter projectAdapter;
    private ProjectAdapter LimitedAdapter;
    private ProjectAdapter TimeLimittAdapter;
    private PagerGalleryView advertisingGallery;
    private LinearLayout spotLl;

    private List<String> advertsList = new ArrayList<>();
    private ImageView homeIv;

    @Override
    protected void init(Bundle savedInstanceState) {

        initTitle("接米");
        initTitleBackgourd(R.color.c_4D4D4D);
        setImgbackgourd(R.mipmap.home_menu_icon, R.mipmap.home_message_icon);

        setPullDownEnabled(false);// 禁掉下拉加载
        setPullUpEnabled(false);// 禁掉上拉加载

        homeActivity = (MainHomeActivity) getActivity();

        View view = LayoutInflater.from(homeActivity).inflate(R.layout.fragment_home, null);
        initView(view);
        scrollView.addView(view);
    }

    private void initView(View view) {
        homeIv = (ImageView) view.findViewById(R.id.home_iv);
        advertisingGallery = (PagerGalleryView) view.findViewById(R.id.home_advertising_gallery_view);
        advertisingGallery.setScaleType(ImageView.ScaleType.CENTER_CROP);
        spotLl = (LinearLayout) view.findViewById(R.id.home_spot_ll);

        selectedLookRl = (RelativeLayout) view.findViewById(R.id.home_selected_look_rl);
        limitedLookRl = (RelativeLayout) view.findViewById(R.id.home_limited_look_rl);
        timeLimitLookRl = (RelativeLayout) view.findViewById(R.id.home_time_limit_look_rl);

        selectedRlv = (RecyclerView) view.findViewById(R.id.home_selected_rlv);
        limitedRlv = (RecyclerView) view.findViewById(R.id.home_limited_rlv);
        timeLimitRlv = (RecyclerView) view.findViewById(R.id.home_time_limit_rlv);

        understandRl = (RelativeLayout) view.findViewById(R.id.home_understand_rl);

        selectedLookRl.setOnClickListener(this);
        limitedLookRl.setOnClickListener(this);
        timeLimitLookRl.setOnClickListener(this);
        understandRl.setOnClickListener(this);

        setSelectedList();
        setLimitedList();
        setTimeLimittList();
        getSelectedListData(0);

        initViewPager(advertsList, advertisingGallery, spotLl);
    }

    @Override
    protected void leftOnclick() {
        super.leftOnclick();
        homeActivity.navView.show();
    }

    @Override
    protected void rightOnclick() {
        super.rightOnclick();

    }

    @Override
    public void onNoDoubleClick(View v) {
        switch (v.getId()) {
            case R.id.home_selected_look_rl:
                Bundle bundle = new Bundle();
                bundle.putString("projectType", "jx");
                JumpManager.gotoActivity(homeActivity, ProjectFilterActivity.class, false, bundle);
                break;

            case R.id.home_limited_look_rl:
                Bundle bundle1 = new Bundle();
                bundle1.putString("projectType", "xl");
                JumpManager.gotoActivity(homeActivity, ProjectFilterActivity.class, false, bundle1);
                break;

            case R.id.home_time_limit_look_rl:
                Bundle bundle2 = new Bundle();
                bundle2.putString("projectType", "xs");
                JumpManager.gotoActivity(homeActivity, ProjectFilterActivity.class, false, bundle2);
                break;

            case R.id.home_understand_rl:
                break;

            default:
                break;
        }
    }


    @Override
    protected void onRefreshFinish() {

    }

    @Override
    protected void onLoadMoreFinish() {

    }

    @Override
    public void LogoutCallback(boolean islogin) {

    }

    private void getSelectedListData(int lastTaskId) {
        List<OkHttpClientManager.Param> params = new ArrayList<>();
        params.add(new OkHttpClientManager.Param("type", "jx"));// 查询范围，任务类型，0：全部1：精选2：限量3：限时
        params.add(new OkHttpClientManager.Param("lastTaskId", "0"));
        params.add(new OkHttpClientManager.Param("limit", "3"));
        OkHttpClientManager.postAsyn(HttpUrl.getInstance().URL_037, new OkHttpClientManager.ResultCallback<List<TaskRecordEntity>>() {
            @Override
            public void onError(String request) {
                LogUtil.i(request);
                getLimitedListData(0);
            }

            @Override
            public void onResponse(List<TaskRecordEntity> resp) {
                if (resp == null || resp.size() == 0) {
                    ToastUtil.show(getContext(), "暂无新数据", Toast.LENGTH_SHORT);
                } else {
                    homeSelectedtList.clear();
                    homeSelectedtList.addAll(resp);
                    setSelectedList();
                }
                getLimitedListData(0);
            }

            @Override
            public void onFinish() {
            }
        }, params, null);
    }

    private void getLimitedListData(int lastTaskId) {
        List<OkHttpClientManager.Param> params = new ArrayList<>();
        params.add(new OkHttpClientManager.Param("type", "xl"));// 查询范围，任务类型，0：全部1：精选2：限量3：限时
        params.add(new OkHttpClientManager.Param("lastTaskId", "0"));
        params.add(new OkHttpClientManager.Param("limit", "3"));
        OkHttpClientManager.postAsyn(HttpUrl.getInstance().URL_037, new OkHttpClientManager.ResultCallback<List<TaskRecordEntity>>() {
            @Override
            public void onError(String request) {
                LogUtil.i(request);
                getTimeLimittListData(0);
            }

            @Override
            public void onResponse(List<TaskRecordEntity> resp) {
                if (resp == null || resp.size() == 0) {
                    ToastUtil.show(getContext(), "暂无新数据", Toast.LENGTH_SHORT);
                } else {
                    homeLimitedList.clear();
                    homeLimitedList.addAll(resp);
                    setLimitedList();
                }
                getTimeLimittListData(0);
            }

            @Override
            public void onFinish() {
            }
        }, params, null);
    }

    private void getTimeLimittListData(int lastTaskId) {
        List<OkHttpClientManager.Param> params = new ArrayList<>();
        params.add(new OkHttpClientManager.Param("type", "xs"));// 查询范围，任务类型，0：全部1：精选2：限量3：限时
        params.add(new OkHttpClientManager.Param("lastTaskId", "0"));
        params.add(new OkHttpClientManager.Param("limit", "3"));
        OkHttpClientManager.postAsyn(HttpUrl.getInstance().URL_037, new OkHttpClientManager.ResultCallback<List<TaskRecordEntity>>() {
            @Override
            public void onError(String request) {
                LogUtil.i(request);
            }

            @Override
            public void onResponse(List<TaskRecordEntity> resp) {
                if (resp == null || resp.size() == 0) {
                    ToastUtil.show(getContext(), "暂无新数据", Toast.LENGTH_SHORT);
                } else {
                    homeTimeLimittList.clear();
                    homeTimeLimittList.addAll(resp);
                    setTimeLimittList();
                }
            }

            @Override
            public void onFinish() {
            }
        }, params, null);
    }

    public class layoutManager extends LinearLayoutManager {
        private boolean isScrollEnabled = true;

        public layoutManager(Context context) {
            super(context);
        }

        public void setScrollEnabled(boolean flag) {
            this.isScrollEnabled = flag;
        }

        @Override
        public boolean canScrollVertically() {
            //Similarly you can customize "canScrollHorizontally()" for managing horizontal scroll
            return isScrollEnabled && super.canScrollVertically();
        }
    }


    private void setSelectedList() {
        if (homeSelectedtList.size() != 0) {
            if (projectAdapter == null) {
                projectAdapter = new ProjectAdapter(getContext(), homeSelectedtList);
                layoutManager layoutManager = new layoutManager(getContext());
                layoutManager.setScrollEnabled(false);
                selectedRlv.setLayoutManager(layoutManager);
                selectedRlv.setAdapter(projectAdapter);
                projectAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
                    @Override
                    public void onItemClick(ViewGroup parent, View view, int position) {
                        Bundle bundle = new Bundle();
                        bundle.putString("taskId", homeSelectedtList.get(position).getTaskId());
                        JumpManager.gotoActivity(getContext(), TaskDetailsActivity.class, false, bundle);
                    }
                });
            } else {
                projectAdapter.refreshList(homeSelectedtList);
            }
        } else {
        }
    }

    private void setLimitedList() {
        if (homeLimitedList.size() != 0) {
            if (LimitedAdapter == null) {
                LimitedAdapter = new ProjectAdapter(getContext(), homeLimitedList);
                layoutManager layoutManager = new layoutManager(getContext());
                layoutManager.setScrollEnabled(false);
                limitedRlv.setLayoutManager(layoutManager);
                limitedRlv.setAdapter(LimitedAdapter);
                LimitedAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
                    @Override
                    public void onItemClick(ViewGroup parent, View view, int position) {
                        Bundle bundle = new Bundle();
                        bundle.putString("taskId", homeLimitedList.get(position).getTaskId());
                        JumpManager.gotoActivity(getContext(), TaskDetailsActivity.class, false, bundle);
                    }
                });
            } else {
                LimitedAdapter.refreshList(homeLimitedList);
            }
        } else {
        }
    }

    private void setTimeLimittList() {
        if (homeTimeLimittList.size() != 0) {
            if (TimeLimittAdapter == null) {
                TimeLimittAdapter = new ProjectAdapter(getContext(), homeTimeLimittList);
                layoutManager layoutManager = new layoutManager(getContext());
                layoutManager.setScrollEnabled(false);
                timeLimitRlv.setLayoutManager(layoutManager);
                timeLimitRlv.setAdapter(TimeLimittAdapter);
                TimeLimittAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
                    @Override
                    public void onItemClick(ViewGroup parent, View view, int position) {
                        Bundle bundle = new Bundle();
                        bundle.putString("taskId", homeTimeLimittList.get(position).getTaskId());
                        JumpManager.gotoActivity(getContext(), TaskDetailsActivity.class, false, bundle);
                    }
                });
            } else {
                TimeLimittAdapter.refreshList(homeTimeLimittList);
            }
        } else {
        }
    }

    /* 初始化广告位2 */
    private void initViewPager(List<String> advertsList, PagerGalleryView mViewPager, LinearLayout jinpinSpotLl) {
        if (!(advertsList != null && advertsList.size() > 0)) {
            homeIv.setVisibility(View.VISIBLE);
            advertisingGallery.setVisibility(View.GONE);
            return;
        } else {
            homeIv.setVisibility(View.GONE);
            advertisingGallery.setVisibility(View.VISIBLE);
        }

        String[] imgurlList = new String[advertsList.size()];
        for (int i = 0; i < advertsList.size(); i++) {
            imgurlList[i] = advertsList.get(i);
        }
        // 轮播图
        mViewPager.startLl(getContext(), imgurlList, 2000, jinpinSpotLl, imgurlList);
        mViewPager.setMyOnItemClickListener(new PagerGalleryView.MyOnItemClickListener() {

            @Override
            public void onItemClick(int curIndex) {

            }
        });
    }
}
